
local goodsId = ARGV[1]

local userId = ARGV[2]

local orderId = ARGV[3]

local addStream = ARGV[4]

local streamKey = ARGV[5]


local stockKey = 'seckill:stock:' .. goodsId

local orderKey = 'seckill:order:' .. goodsId


if(tonumber(redis.call('get', stockKey)) <= 0) then
    return 1
end

if(redis.call('sismember', orderKey, userId) == 1) then
    return 2
end

redis.call('incrby', stockKey, -1)

redis.call('sadd', orderKey, userId)
if(addStream=="true") then
    redis.call('xadd', streamKey, '*', 'userId', userId, 'goodsId', goodsId)
end
return 0